//
//  FolderItemsDownload.m
//  Alfresco
//
//  Created by Michael Muller on 10/21/09.
//  Copyright 2009 Michael J Muller. All rights reserved.
//

#import "FolderItemsDownload.h"
#import "RepositoryItem.h"
#import "Utility.h"

@implementation FolderItemsDownload

@synthesize children;
@synthesize currentCMISName;
@synthesize elementBeingParsed;
@synthesize context;
@synthesize parentTitle;

- (void) dealloc {
	[children release];
	[elementBeingParsed release];
	[super dealloc];
}

- (FolderItemsDownload *) initWithNode:(NSString *)node delegate: (id <AsynchronousDownloadDelegate>) del {
	NSString *h = userPrefHostname();
	NSString *p = userPrefPort();
	NSString *protocol = userPrefProtocol();
	
	NSString *urlStr = [[NSString alloc] initWithFormat:@"%@://%@:%@%@/children", protocol, h, p, node];
	NSURL *u = [NSURL URLWithString:urlStr];
	[urlStr release];
	return (FolderItemsDownload *) [self initWithURL:u delegate:del];
}

- (FolderItemsDownload *) initWithGUID:(NSString *)guid delegate: (id <AsynchronousDownloadDelegate>) del {
	NSString *w = userPrefWebApp();
	NSString *node = [[NSString alloc] initWithFormat:@"%@/service/api/node/workspace/SpacesStore/%@", w, guid];
	FolderItemsDownload *down = [self initWithNode:node delegate:del];
	[node release];
	return down;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

	// log the response
	NSString *responseAsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	//NSLog(@"**** async result: %@", responseAsString);
	[responseAsString release];
	
	// create an array to hold the folder items
	NSMutableArray *c = [[NSMutableArray alloc] init];
	self.children = c;
	[c release];
	
	// create a parser and parse the xml
	NSXMLParser *parser = [NSXMLParser alloc];
	
	if (userPrefEnableAmpersandHack()) {
		NSString *convert = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

		NSString *enc1 = createStringByEscapingAmpersandsInsideTagsOfString(convert, @"<cmis:propertyString cmis:name=\"Name\"><cmis:value>", @"</cmis:value></cmis:propertyString>");
		NSString *enc2 = createStringByEscapingAmpersandsInsideTagsOfString(enc1, @"<title>", @"</title>");
		NSString *enc3 = createStringByEscapingAmpersandsInsideTagsOfString(enc2, @"<summary>", @"</summary>");
		
		[parser initWithData:[enc3 dataUsingEncoding:NSUTF8StringEncoding]];
		
		[convert release];
		[enc1 release];
		[enc2 release];
		[enc3 release];
	}
	else {
		[parser initWithData:self.data];
	}
	
	[parser setDelegate:self];
	[parser parse];
	[parser release];
	
	// sort the docs & folders by title
	[self.children sortUsingSelector:@selector(compareTitles:)];
	
	// if the user has selected the preference to hide "dot" files, then filter those from the list
	if (!userPrefShowHiddenFiles()) {
		for (int i = [self.children count] - 1; i >= 0; i--) {
			RepositoryItem *item = [self.children objectAtIndex:i];
			if ([item.title hasPrefix:@"."]) {
				[self.children removeObjectAtIndex:i];
			}
		}
	}
	
	[super connectionDidFinishLoading:connection];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

	// if this is a new entry, create a repository item and add it to the list
	if ([elementName isEqualToString:@"entry"]) {
		RepositoryItem *item = [[RepositoryItem alloc] init];
		[self.children addObject:item];
		[item release];
	}
	
	if ([elementName isEqualToString:@"content"]) {
		[[self.children lastObject] setContentLocation: [attributeDict objectForKey:@"src"]];
	}
	
	if ([elementName hasPrefix:@"cmis:property"]) {
		self.currentCMISName = [attributeDict objectForKey:@"cmis:name"] ? [attributeDict objectForKey:@"cmis:name"] : [attributeDict objectForKey:@"propertyDefinitionId"];
	}
	
	self.elementBeingParsed = elementName;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	if ([elementName hasPrefix:@"cmis:property"]) {
		self.currentCMISName = nil;
	}
	self.elementBeingParsed = nil;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	RepositoryItem *currentItem = [self.children lastObject];
	
	if ([self.elementBeingParsed isEqualToString:@"title"]) {
		currentItem.title = currentItem.title ? [currentItem.title stringByAppendingString:string] : string;
	}
	else if ([self.elementBeingParsed isEqualToString:@"content"]) {
		currentItem.guid = currentItem.guid ? [currentItem.guid stringByAppendingString:string] : string;
	}
	else if ([self.elementBeingParsed isEqualToString:@"cmis:value"]) {
		if ([self.currentCMISName isEqualToString:@"LastModifiedBy"] || [self.currentCMISName isEqualToString:@"cmis:lastModifiedBy"]) {
			currentItem.lastModifiedBy = currentItem.lastModifiedBy ? [currentItem.lastModifiedBy stringByAppendingString:string] : string;
		}
		else if ([self.currentCMISName isEqualToString:@"LastModificationDate"] || [self.currentCMISName isEqualToString:@"cmis:lastModificationDate"]) {
			currentItem.lastModifiedDate = currentItem.lastModifiedDate ? [currentItem.lastModifiedDate stringByAppendingString:string] : string;
		}
		else if ([self.currentCMISName isEqualToString:@"BaseType"] || [self.currentCMISName isEqualToString:@"cmis:baseTypeId"]) {
			currentItem.fileType = currentItem.fileType ? [currentItem.fileType stringByAppendingString:string] : string;
		}
	}
}

@end

/*
 
 sample getchildren response:
 
 <?xml version="1.0" encoding="UTF-8"?>
 <feed xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/" xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/" xmlns:alf="http://www.alfresco.org" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
 <author><name>System</name></author>
 <generator version="3.2.0 (r2 2440)">Alfresco (Community)</generator>
 <icon>https://dms.xwave.ch:443/alfresco/images/logo/AlfrescoLogo16.ico</icon>
 <id>urn:uuid:031a73a3-98e2-4795-b23f-816a10ad564f-children</id>
 <link rel="service" href="https://dms.xwave.ch:443/alfresco/service/cmis"/>
 <link rel="self" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f/children"/>
 <link rel="via" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f"/>
 <link rel="down" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f/descendants" type="application/cmistree+xml"/>
 <link rel="http://docs.oasis-open.org/ns/cmis/link/200908/foldertree" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f/tree" type="application/cmistree+xml"/>
 <link rel="first" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f/children?pageNo=1&amp;pageSize=-1&amp;guest=&amp;format=atomfeed" type="application/atom+xml;type=feed"/>
 <link rel="last" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f/children?pageNo=1&amp;pageSize=-1&amp;guest=&amp;format=atomfeed" type="application/atom+xml;type=feed"/>
 <title>Company Home Children</title>
 <updated>2010-01-07T15:56:34.767+03:00</updated>
 <opensearch:totalResults>7</opensearch:totalResults>
 <opensearch:startIndex>0</opensearch:startIndex>
 <opensearch:itemsPerPage>-1</opensearch:itemsPerPage>
 <cmisra:numItems>7</cmisra:numItems>
 <entry>
 <author><name>System</name></author>
 <content>0874d76c-0369-4d99-9c54-72be3d59389c</content>
 <id>urn:uuid:0874d76c-0369-4d99-9c54-72be3d59389c</id>
 <link rel="self" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c"/>
 <link rel="edit" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c"/>
 <link rel="http://docs.oasis-open.org/ns/cmis/link/200908/allowableactions" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c/allowableactions"/>
 <link rel="http://docs.oasis-open.org/ns/cmis/link/200908/relationships" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c/rels"/>
 <link rel="up" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/031a73a3-98e2-4795-b23f-816a10ad564f" type="application/atom+xml;type=entry"/>
 <link rel="down" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c/children" type="application/atom+xml;type=feed"/>
 <link rel="down" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c/descendants" type="application/cmistree+xml"/>
 <link rel="http://docs.oasis-open.org/ns/cmis/link/200908/foldertree" href="https://dms.xwave.ch:443/alfresco/service/cmis/s/workspace:SpacesStore/i/0874d76c-0369-4d99-9c54-72be3d59389c/tree" type="application/cmistree+xml"/>
 <link rel="describedby" href="https://dms.xwave.ch:443/alfresco/service/cmis/type/F:st:sites"/>
 <link rel="service" href="https://dms.xwave.ch:443/alfresco/service/cmis"/>
 <published>2010-01-07T15:56:46.830+03:00</published>
 <summary>Site Collaboration Spaces</summary>
 <title>Sites</title>
 <updated>2010-01-07T15:56:46.853+03:00</updated>
 <app:edited>2010-01-07T15:56:46.853+03:00</app:edited>
 <alf:icon>https://dms.xwave.ch:443/alfresco/images/icons/space-icon-default-16.gif</alf:icon>
 <cmisra:object>
 <cmis:properties>
 <cmis:propertyId propertyDefinitionId="cmis:allowedChildObjectTypeIds"/>
 <cmis:propertyId propertyDefinitionId="cmis:objectTypeId"><cmis:value>F:st:sites</cmis:value></cmis:propertyId>
 <cmis:propertyString propertyDefinitionId="cmis:lastModifiedBy"><cmis:value>System</cmis:value></cmis:propertyString>
 <cmis:propertyString propertyDefinitionId="cmis:path"><cmis:value>/Sites</cmis:value></cmis:propertyString>
 <cmis:propertyString propertyDefinitionId="cmis:name"><cmis:value>Sites</cmis:value></cmis:propertyString>
 <cmis:propertyString propertyDefinitionId="cmis:createdBy"><cmis:value>System</cmis:value></cmis:propertyString>
 <cmis:propertyId propertyDefinitionId="cmis:objectId"><cmis:value>workspace://SpacesStore/0874d76c-0369-4d99-9c54-72be3d59389c</cmis:value></cmis:propertyId>
 <cmis:propertyDateTime propertyDefinitionId="cmis:creationDate"><cmis:value>2010-01-07T15:56:46.830+03:00</cmis:value></cmis:propertyDateTime>
 <cmis:propertyString propertyDefinitionId="cmis:changeToken"/>
 <cmis:propertyId propertyDefinitionId="cmis:baseTypeId"><cmis:value>cmis:folder</cmis:value></cmis:propertyId>
 <cmis:propertyDateTime propertyDefinitionId="cmis:lastModificationDate"><cmis:value>2010-01-07T15:56:46.853+03:00</cmis:value></cmis:propertyDateTime>
 <cmis:propertyId propertyDefinitionId="cmis:parentId"><cmis:value>workspace://SpacesStore/031a73a3-98e2-4795-b23f-816a10ad564f</cmis:value></cmis:propertyId>
 </cmis:properties>
 </cmisra:object>
 <cmisra:pathSegment>Sites</cmisra:pathSegment>
 </entry>
 
 OLD sample getchildren response:
 
 <entry>
 <author><name>pmahon</name></author>
 <content>54186503-ed0c-4037-98d4-d071fbe8368e</content>
 <id>urn:uuid:54186503-ed0c-4037-98d4-d071fbe8368e</id>
 <link rel="self" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e"/>
 <link rel="edit" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e"/>
 <link rel="cmis-allowableactions" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e/permissions"/>
 <link rel="cmis-relationships" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e/associations"/>
 <link rel="cmis-parent" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/56ed3dfc-28e1-4c62-98df-0b52f7c94fe2"/>
 <link rel="cmis-folderparent" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e/parent"/>
 <link rel="cmis-children" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e/children"/>
 <link rel="cmis-descendants" href="http://cm.ziaconsulting.com:80/alfresco/service/api/node/workspace/SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e/descendants"/>
 <link rel="cmis-type" href="http://cm.ziaconsulting.com:80/alfresco/service/api/type/folder"/>
 <link rel="cmis-repository" href="http://cm.ziaconsulting.com:80/alfresco/service/api/repository"/>
 <published>2009-06-30T23:33:35.564Z</published>
 <summary></summary>
 <title>blog</title>
 <updated>2009-06-30T23:33:35.578Z</updated>
 <cmis:object>
 <cmis:properties>
 <cmis:propertyId cmis:name="ObjectId"><cmis:value>workspace://SpacesStore/54186503-ed0c-4037-98d4-d071fbe8368e</cmis:value></cmis:propertyId>
 <cmis:propertyString cmis:name="BaseType"><cmis:value>folder</cmis:value></cmis:propertyString>
 <cmis:propertyString cmis:name="ObjectTypeId"><cmis:value>folder</cmis:value></cmis:propertyString>
 <cmis:propertyString cmis:name="CreatedBy"><cmis:value>pmahon</cmis:value></cmis:propertyString>
 <cmis:propertyDateTime cmis:name="CreationDate"><cmis:value>2009-06-30T23:33:35.564Z</cmis:value></cmis:propertyDateTime>
 <cmis:propertyString cmis:name="LastModifiedBy"><cmis:value>pmahon</cmis:value></cmis:propertyString>
 <cmis:propertyDateTime cmis:name="LastModificationDate"><cmis:value>2009-06-30T23:33:35.578Z</cmis:value></cmis:propertyDateTime>
 <cmis:propertyString cmis:name="Name"><cmis:value>blog</cmis:value></cmis:propertyString>
 <cmis:propertyId cmis:name="ParentId"><cmis:value>workspace://SpacesStore/56ed3dfc-28e1-4c62-98df-0b52f7c94fe2</cmis:value></cmis:propertyId>
 </cmis:properties>
 </cmis:object>
 <cmis:terminator/>
 <app:edited>2009-06-30T23:33:35.578Z</app:edited>
 <alf:icon>http://cm.ziaconsulting.com:80/alfresco/images/icons/space-icon-default-16.gif</alf:icon>
 </entry>
 
 */
